<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use FormBuilder\Factory\Elm;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\admin\validate\MassageAds as ValidateMassageAds;
use plugin\ycMassage\app\model\MassageAds;
use plugin\ycMassage\app\model\PluginArticles;
use plugin\ycMassage\utils\enum\AdsPage;
use plugin\ycMassage\utils\enum\InnerPage;
use plugin\ycMassage\utils\enum\State;
use think\facade\Db;
use think\Request;

class AdsController extends BaseController
{
    public function indexGetTable(Request $request, $position = 'banner')
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->checkboxConfig();
        $builder->addActionOptions('操作', [
            'width' => 220
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addBottomButton('deleteAll', '删除', [
            'api'    => $this->pluginPrefix . '/admin/Ads/deleteAll',
            'type'      => 'confirm',
            'method' => 'delete'
        ], [
            'type' => 'error',
        ], [
            'type' => 'error',
        ]);
        $builder->addTopButton('add', '添加广告', [
            'api'       => $this->pluginPrefix . '/admin/Ads/create',
            'path' => '/Ads/create',
            'type'      => 'modal',
            'queryParams' => [
                'position' => $position
            ]
        ], [
            'title' => '添加广告',
        ], [
            'type' => 'success'
        ]);
        $builder->addRightButton('edit', '修改', [
            'api'    => $this->pluginPrefix . '/admin/Ads/update',
            'path' => '/Ads/update',
            'type'      => 'modal'
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('del', '删除', [
            'type'   => 'confirm',
            'api'    => $this->pluginPrefix . '/admin/Ads/delete',
            'method' => 'delete'
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认删除该数据',
        ], [
            'type' => 'error',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90,
            'type' => 'checkbox'
        ]);
        $builder->addColumnEle('image', '图片', [
            'width' => 60,
            'params' => [
                'type' => 'image',
            ],
        ])
            ->addColumn('title', '名称')
            ->addColumnEle('page', '页面', [
                'width'  => 90,
                'params' => [
                    'type'    => 'tags',
                    'options' => AdsPage::dictOptions(),
                ],
            ])
            ->addColumn('alias.title', '关联标题')
            ->addColumn('url', '链接')
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'switch',
                    'api' => $this->pluginPrefix . '/admin/Ads/updateState',
                    'checked' => [
                        'text' => '可用',
                        'value' => 1
                    ],
                    'unchecked' => [
                        'text' => '不可用',
                        'value' => 0
                    ]
                ],
            ])
            ->addColumn('create_at', '创建时间', [
                'width' => 160,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $position = $request->get('position', 'banner');
        $where = [
            ['position', '=', $position],
            ['saas_appid', '=', $request->saas_appid]
        ];
        $data = MassageAds::where($where)
            ->order('sort asc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                $item->image = UploadService::url($item->image);
                $item->image_2 = UploadService::url($item->image_2);
                switch ($item->page) {
                    case 'ARTICLE':
                        $article = new \stdClass;
                        $article->title = 'dwa';
                        $item->alias = $article;
                        break;
                }
            });
        return $this->successRes($data);
    }
    public function bannerGetTable(Request $request)
    {
        return $this->indexGetTable($request);
    }
    public function banner(Request $request)
    {
        return $this->index($request);
    }
    public function home_quickGetTable(Request $request)
    {
        return $this->indexGetTable($request, 'home_quick');
    }
    public function home_quick(Request $request)
    {
        return $this->index($request);
    }
    public function agentGetTable(Request $request)
    {
        return $this->indexGetTable($request, 'agent');
    }
    public function agent(Request $request)
    {
        return $this->index($request);
    }
    public function homeMoreGetTable(Request $request)
    {
        return $this->indexGetTable($request, 'home_more');
    }
    public function homeMore(Request $request)
    {
        return $this->index($request);
    }
    public function tabbarGetTable(Request $request)
    {

        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->checkboxConfig();
        $builder->addActionOptions('操作', [
            'width' => 220
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addBottomButton('deleteAll', '删除', [
            'api'    => $this->pluginPrefix . '/admin/Ads/deleteAll',
            'type'      => 'confirm',
            'method' => 'delete'
        ], [
            'type' => 'error',
        ], [
            'type' => 'error',
        ]);
        $builder->addTopButton('add', '添加Tab', [
            'api'       => $this->pluginPrefix . '/admin/Ads/tabbarCreate',
            'path' => '/Ads/tabbarCreate',
            'type'      => 'modal',
            'queryParams' => [
                'position' => 'tabbar'
            ]
        ], [
            'title' => '添加Tab',
        ], [
            'type' => 'success'
        ]);
        $builder->addRightButton('edit', '修改', [
            'api'    => $this->pluginPrefix . '/admin/Ads/tabbarUpdate',
            'path' => '/Ads/tabbarUpdate',
            'type'      => 'modal'
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('del', '删除', [
            'type'   => 'confirm',
            'api'    => $this->pluginPrefix . '/admin/Ads/delete',
            'method' => 'delete'
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认删除该数据',
        ], [
            'type' => 'error',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90,
            'type' => 'checkbox'
        ]);
        $builder->addColumnEle('image', '未选中', [
            'width' => 100,
            'params' => [
                'type' => 'image',
            ],
        ]);
        $builder->addColumnEle('image_2', '选中', [
            'width' => 100,
            'params' => [
                'type' => 'image',
            ],
        ])
            ->addColumn('title', '名称')
            ->addColumnEle('page', '页面', [
                'width'  => 90,
                'params' => [
                    'type'    => 'tags',
                    'options' => AdsPage::dictOptions(),
                ],
            ])
            ->addColumn('url', '链接')
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'switch',
                    'api' => $this->pluginPrefix . '/admin/Ads/updateState',
                    'checked' => [
                        'text' => '可用',
                        'value' => 1
                    ],
                    'unchecked' => [
                        'text' => '不可用',
                        'value' => 0
                    ]
                ],
            ])
            ->addColumn('create_at', '创建时间', [
                'width' => 160,
            ]);
        return $this->successRes($builder->create());
    }
    public function tabbar(Request $request)
    {
        return $this->index($request);
    }
    public function tabbarCreate(Request $request)
    {
        if (MassageAds::where(['saas_appid' => $request->saas_appid, 'position' => 'tabbar'])->count() >= 5) {
            return $this->fail('tabbar最多5个');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $D['position'] = 'tabbar';
            $D['image'] = UploadService::path($D['image']);
            $D['image_2'] = UploadService::path($D['image_2']);
            hpValidate(ValidateMassageAds::class, $D);
            $MassageAds = new MassageAds();
            $D['saas_appid'] = $request->saas_appid;
            if ($MassageAds->save($D)) {
                return $this->success('添加成功');
            }
            return $this->fail('添加失败');
        }
        $builder = $this->getTabbarForm($request);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function tabbarUpdate(Request $request)
    {
        $id = $request->get('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        $MassageAds = MassageAds::where($where)->find();
        if (!$MassageAds) {
            return $this->fail('该广告不存在');
        }
        $MassageAds->image = [UploadService::url($MassageAds->image)];
        if ($MassageAds->image_2) {
            $MassageAds->image_2 = [UploadService::url($MassageAds->image_2)];
        }else{
            $MassageAds->image_2 = [];
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $D['position'] = 'tabbar';
            $D['image'] = UploadService::path($D['image']);
            $D['image_2'] = UploadService::path($D['image_2']);
            hpValidate(ValidateMassageAds::class, $D);
            $D['saas_appid'] = $request->saas_appid;
            if ($MassageAds->save($D)) {
                return $this->success('添加成功');
            }
            return $this->fail('添加失败');
        }
        $builder = $this->getTabbarForm($request);
        $data = $builder->setData($MassageAds)->create();
        return $this->successRes($data);
    }
    private function getTabbarForm($request)
    {
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('image', 'uploadify', '未选中(30px*30px)', '', [
            'col' => 6,
            'props' => [
                'type' => 'image',
                'limit' => 1,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $builder->addComponent('image_2', 'uploadify', '选中(30px*30px)', '', [
            'col' => 6,
            'props' => [
                'type' => 'image',
                'limit' => 1,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $builder->addRow('sort', 'number', '排序', 99, [
            'col' => 12,
            'props' => [
                'min' => 0,
                'max' => 9999,
                'step' => 1,
                'controls' => false,
            ],
        ]);
        $builder->addRow('title', 'input', '名称', '', [
            'col' => 12,
        ]);
        $builder->addRow('state', 'radio', '状态', 1, [
            'col' => 12,
            'options' => State::getOptions()
        ]);
        $builder->addRow('page', 'select', '页面', AdsPage::SWITCH['value'], [
            'col' => 12,
            'options' => AdsPage::getOptions(),
            // 使用联动组件
            'control' => $this->getPageControlList($request)
        ]);
        return $builder;
    }
    private function getPageControlList(Request $request)
    {
        $control = [
            [
                'value' => AdsPage::ARTICLE['value'],
                'where' => '==',
                'rule' => [
                    Elm::select('alias_id', '选择文章')
                        ->col([
                            'span' => 12
                        ])
                        ->options(PluginArticles::getOptions($request->saas_appid))
                        ->props([
                            'filterable' => true,
                            'placeholder' => '请选择文章',
                        ])
                ],
            ],
            [
                'value' => AdsPage::CUSTOM['value'],
                'where' => '==',
                'rule' => [
                    Elm::input('url', '链接')
                        ->col([
                            'span' => 12
                        ])
                        ->props([
                            'placeholder' => '请输入链接',
                        ])
                ],
            ],
            [
                'value' => AdsPage::INNER['value'],
                'where' => '==',
                'rule' => [
                    Elm::select('url', '选择或输入链接')
                        ->col([
                            'span' => 12
                        ])
                        ->options(InnerPage::getOptions())
                        ->props([
                            'filterable' => true,
                            'placeholder' => '请选择或输入链接',
                            'allowCreate' => true,
                            'defaultFirstOption' => true
                        ])
                ],
            ],
            [
                'value' => AdsPage::SWITCH['value'],
                'where' => '==',
                'rule' => [
                    Elm::select('url', '选择Tab页面')
                        ->col([
                            'span' => 12
                        ])
                        ->options([
                            [
                                'label' => '首页',
                                'value' => '/pages/index/index'
                            ],
                            [
                                'label' => '技师',
                                'value' => '/pages/technician/index'
                            ],
                            [
                                'label' => '订单',
                                'value' => '/pages/order/list'
                            ],
                            [
                                'label' => '动态',
                                'value' => '/pages/moments/index'
                            ],
                            [
                                'label' => '我的',
                                'value' => '/pages/user/index'
                            ]
                        ])
                        ->props([
                            'filterable' => true,
                            'placeholder' => '请选择Tab页面',
                        ])
                ],
            ]
        ];
        return $control;
    }
    public function create(Request $request)
    {
        if ($request->method() === 'POST') {
            $D = $request->post();
            $D['position'] = $request->get('position', 'banner');
            $D['image'] = UploadService::path($D['image']);
            hpValidate(ValidateMassageAds::class, $D);
            $MassageAds = new MassageAds();
            $D['saas_appid'] = $request->saas_appid;
            if ($MassageAds->save($D)) {
                return $this->success('添加成功');
            }
            return $this->fail('添加失败');
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('image', 'uploadify', '图片', '', [
            'col' => 6,
            'props' => [
                'type' => 'image',
                'limit' => 1,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $builder->addRow('sort', 'number', '排序', 99, [
            'col' => 6,
            'props' => [
                'min' => 0,
                'max' => 9999,
                'step' => 1,
                'controls' => false,
            ],
        ]);
        $builder->addRow('title', 'input', '名称', '', [
            'col' => 12,
        ]);
        $builder->addRow('state', 'radio', '状态', 1, [
            'col' => 12,
            'options' => State::getOptions()
        ]);
        $builder->addRow('page', 'select', '页面', '', [
            'col' => 12,
            'options' => AdsPage::getOptions(),
            // 使用联动组件
            'control' => $this->getPageControlList($request)
        ]);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function update(Request $request)
    {
        $id = $request->get('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        $MassageAds = MassageAds::where($where)->find();
        if (!$MassageAds) {
            return $this->fail('该广告不存在');
        }
        $MassageAds->image = [UploadService::url($MassageAds->image)];
        if ($request->method() === 'POST') {
            $D = $request->post();
            $D['position'] = $request->get('position', 'banner');
            $D['image'] = UploadService::path($D['image']);
            hpValidate(ValidateMassageAds::class, $D);
            $D['saas_appid'] = $request->saas_appid;
            if ($MassageAds->save($D)) {
                return $this->success('添加成功');
            }
            return $this->fail('添加失败');
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('image', 'uploadify', '图片', '', [
            'col' => 6,
            'props' => [
                'type' => 'image',
                'limit' => 1,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $builder->addRow('sort', 'number', '排序', 99, [
            'col' => 6,
            'props' => [
                'min' => 0,
                'max' => 9999,
                'step' => 1,
                'controls' => false,
            ],
        ]);
        $builder->addRow('title', 'input', '名称', '', [
            'col' => 12,
        ]);
        $builder->addRow('state', 'radio', '状态', 1, [
            'col' => 12,
            'options' => State::getOptions()
        ]);
        $builder->addRow('page', 'select', '页面', '', [
            'col' => 12,
            'options' => AdsPage::getOptions(),
            // 使用联动组件
            'control' => $this->getPageControlList($request)
        ]);
        $data = $builder->setData($MassageAds)->create();
        return $this->successRes($data);
    }
    public function updateState(Request $request)
    {
        $id = $request->post('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        $MassageAds = MassageAds::where($where)->find();
        if (!$MassageAds) {
            return $this->fail('该广告不存在');
        }
        $MassageAds->state = $request->post('value');
        if ($MassageAds->save()) {
            return $this->success('修改成功');
        }
        return $this->fail('修改失败');
    }
    public function delete(Request $request)
    {
        $id = $request->post('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        $MassageAds = MassageAds::where($where)->find();
        if (!$MassageAds) {
            return $this->fail('该广告不存在');
        }
        if ($MassageAds->delete()) {
            return $this->success('删除成功');
        }
        return $this->fail('删除失败');
    }
    public function deleteAll(Request $request)
    {
        $id = $request->post('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', 'in', $id]
        ];
        Db::startTrans();
        try {
            $MassageAds = MassageAds::where($where)->select();
            foreach ($MassageAds as $item) {
                $item->delete();
            }
            Db::commit();
            return $this->success('删除成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail('删除失败');
        }
    }
}
